<?php

	
    	
	$url = "https://api.twitter.com/1.1/users/show.json?";

	$oauth_access_token = '20862563-7A4HJ2Ta3pdAmseW5vZmoHXG6gXM5CAqH2aiKzANt';
	$oauth_access_token_secret = 'xHgGHLtllnD4CBqwRSMZWOjFv65Xn7mvllIp5Jp238';
	$consumer_key = 'BrTZa4y7WjufT1jkKPF2ww';
	$consumer_secret = 'sGrjhB2exsI0gSJB33e2gjcS2S8xHkTzbjvKNMNGhDs';


                
	require('tmhOAuth/tmhOAuth.php');
	require('tmhOAuth/tmhUtilities.php');
 	
 	$arrOAuth = array(
		"consumer_key" => $consumer_key, 
		"consumer_secret" => $consumer_secret, 
		"user_token" => $oauth_access_token, 
		"user_secret" => $oauth_access_token_secret,
		"curl_ssl_verifypeer" => false);
		
	$tmhOAuth = new tmhOAuth($arrOAuth);
 	
 	require_once('140dev_config.php');
	require_once('db_lib.php');
	$oDB = new db;
    
    //$con = mysql_connect($db_host,$db_user,$db_password);
    //$con = mysql_connect('mysql1.alwaysdata.com','62465_pcocko','sygnium');
	if(!$oDB)
  	{
  		die('Could not connect: ' . mysql_error());
  	}

	//mysql_select_db('freshbuzzing_1', $con);
	//$result = mysql_query("SELECT * FROM MAST_TWITTERS_ACCOUNTS");
	if(isset($_GET['id_resto']))
		$result = $oDB->select("SELECT DS_SCREEN_NAME, ID_LAST_TWEET FROM MAST_TWITTER_ACCOUNTS T1 INNER JOIN MAST_RESTAURANTS T2 ON T1.DS_SCREEN_NAME = T2.DS_REST_TWITTER WHERE T2.ID_RESTAURANT = '" . $_GET['id_resto'] . "' AND BL_PARSE=1");
	else
		$result = $oDB->select('SELECT DS_SCREEN_NAME, ID_LAST_TWEET FROM MAST_TWITTER_ACCOUNTS WHERE BL_PARSE=1 ORDER BY DT_LAST_DATE_UPDATE ASC LIMIT 180');
	
	while($row = mysqli_fetch_row($result))
  	{
  		//$arrParams = array('screen_name' => $row[1]);
  		$arrParams = array('screen_name' => $row[0]);
		$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/users/show.json'), $arrParams);
 
		$response = $tmhOAuth->response['response'];
	
		$user = json_decode($response, true);
		
		
 		$hoy = date("Y-m-d 00:00:00");
 		$oDB->delete('HIST_TWITTER_ACCOUNTS',"DS_SCREEN_NAME='" . $row[0] ."' AND DT_TIMESTAMP='" . $hoy . "'");
 		$oDB->insert('HIST_TWITTER_ACCOUNTS',"DS_SCREEN_NAME='" . $row[0] . "', DT_TIMESTAMP='" . $hoy . "', NUM_FOLLOWERS=" . $user['followers_count'] . ", NUM_FAVOURITES=" . $user['favourites_count']);
 		
 		if($row[1] == -1)
 			$since_id = 1;
 		else
 			$since_id = $row[1];
 		// Actualiza el timeline del usuario
 		$arrParams = array('screen_name' => $row[0], 'count' => '5', 'exclude_replies' => 'false', 'since_id' => $since_id);
 		//$arrParams = array('screen_name' => $row[1], 'count' => '1', 'exclude_replies' => 'false');
 		//$arrParams = array('screen_name' => 'SuculentBCN');
		$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline.json'), $arrParams);
		$response = $tmhOAuth->response['response'];
	
		$timeline = json_decode($response);
		
		$max_tweet_id = -1;
		/*
		 			print_r('$since_id: ' . $since_id);
				echo '<pre>';
 			print_r($timeline);
 			echo '</pre>';
		*/
		foreach($timeline as $tweet_object) {
			
			$tweet_id = $tweet_object->id_str;
			$text = $tweet_object->text;
 	
			
			$pos = strrpos($text, $row[0]);
			if($pos == false)
			{
				// If there's a ", ', :, or ; in object elements, serialize() gets corrupted 
				// You should also use base64_encode() before saving this
				//$tweet_json = json_decode($tweet_object);
    			$raw_tweet = base64_encode(serialize($tweet_object));
		
    			$field_values = 'DS_RAW_TWEET = "' . $raw_tweet . '", ID_TWEET = ' . $tweet_id;
    			$oDB->insert('TMP_TWITTER_JSON_CACHE',$field_values);
    		}
    		if($tweet_id > $max_tweet_id)
    			$max_tweet_id = $tweet_id;			
		}
		if(count($timeline) == 0)
			$max_tweet_id = $row[1];
		
		$oDB->update('MAST_TWITTER_ACCOUNTS', 'DT_LAST_DATE_UPDATE=NOW(), NUM_FOLLOWERS = ' . $user['followers_count'] . ', ID_LAST_TWEET = ' . $max_tweet_id . ", ID_USER_TW = '" . $user['id_str'] . "'", "DS_SCREEN_NAME = '" . $row[0] . "'");
	


	
 		
  	}
 	 /*
 	 // SIEMPRE TRAE 15 PORQUE ES EL RATE LIMIT DE TWITTER              
	$result = $oDB->select('SELECT ID_USER_TWITTER FROM MAST_TWITTER_USERS order by DT_LAST_UPDATE asc LIMIT 15;');
	while($row = mysqli_fetch_row($result))
  	{
  		// GUARDA LOS IDs DE LOS SEGUIDORES DE CADA USUARIO
  		$user_id = $row[0];
  		$arrParams = array('user_id' => $user_id,'stringify_ids' => 'true');
  		
		$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/followers/ids.json'), $arrParams);
 
		$response = $tmhOAuth->response['response'];
		
		$oDB->update('MAST_TWITTER_USERS',"DT_LAST_UPDATE=NOW(),DS_FOLLOWERS_IDS='" . $response . "'","ID_USER_TWITTER='" . $user_id . "'");
		
		// GUARDA LA INFORMACION DE LAS LISTAS A LA QUE PETERTENECE EL USUARIO
		$arrParams = array('user_id' => $user_id );
		$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/lists/memberships.json'), $arrParams);
		$response = $tmhOAuth->response['response'];
		$lists_all = json_decode($response);
		foreach($lists_all->lists as $list_object) {
			$list_id = $list_object->id_str;
			$name = $list_object->name;
			$uri = $list_object->uri;
			$full_name = $list_object->full_name;
			$member_count = $list_object->member_count;
			$created_at = $oDB->date($list_object->created_at);
			
			$field_values = "ID_LIST_TWITTER = '" . $list_id . "', " .
				"ID_USER_TWITTER = '" . $user_id . "', " .
				"DS_NAME = '" . str_replace($name,"'","''") . "', " .
				"DS_URI = '" . $uri . "', " .
				"DS_FULL_NAME = '" . $full_name . "', " .
				"NUM_MEMBER_COUNT = " . $member_count . ", " .
				"DT_CREATED_AT = '" . $created_at . "', " .
				"DT_LAST_UPDATED = NOW() ";
			if ($oDB->in_table('MAST_TWITTER_MEMBER_LISTS','ID_USER_TWITTER="' . $user_id . '" AND ID_LIST_TWITTER="' . $list_id . '"')) {
      			$oDB->update('MAST_TWITTER_MEMBER_LISTS',$field_values,'ID_USER_TWITTER = "' . $user_id . '" AND ID_LIST_TWITTER="' . $list_id . '"');
			} else {			
      			$oDB->insert('MAST_TWITTER_MEMBER_LISTS',$field_values);
    		}
				
		}
		echo '<pre>';

 		echo '</pre>';
 		
	}*/
	               
?>
